package com.action.api;

import com.bean.Menu;
import com.blade.mvc.annotation.GetRoute;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.util.MenuUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Path
public class IndexAction {

    @GetRoute("/")
    public void renderIndex(Response response, Request request) {
        List<Menu> menus = MenuUtil.generateMenu();
        request.attribute("menus", menus);
        response.render("index");
    }



    @GetRoute("/show")
    public void show(Response response, Request request) {
        String baseUrl = request.query("url").get().trim();
        String url = baseUrl.substring(0, baseUrl.lastIndexOf(File.separator));
        File file = new File(url);

        List<String> times = new ArrayList<>();
        String baseName = baseUrl.substring(baseUrl.lastIndexOf(File.separator) + 1, baseUrl.length());
        System.out.println(baseName);
        if (file.isDirectory()) {
            String[] list = file.list();
            //取时间.
            for (String s : list) {

                String fileName = s.substring(0, s.lastIndexOf("."));
                String name = fileName.substring(0, fileName.length() - 8);
                int i = name.lastIndexOf("-");
                String vx = name.substring(0, i);
                String time = fileName.substring(vx.length() + 1);
                if (!times.contains(time)) {
                    times.add(time);
                }
            }
        }

        // region文件时间顺数排列
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");

        // 降序排列时间
        List<String> allDates = new LinkedList<>();

        // 转换成日期类型临时保存
        List<Date> tmp = new LinkedList<>();
        for (String s : times) {
            try {
                tmp.add(sdf.parse(s));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        Collections.sort(tmp);
        Collections.reverse(tmp);
        for (Date date : tmp) {
            allDates.add(sdf.format(date));
        }
        // endregion
        List<Menu> menus = MenuUtil.generateMenu();
        request.attribute("menus", menus);
        request.attribute("baseName", baseName);
        try {
            request.attribute("basePath", URLDecoder.decode(url, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        request.attribute("times", allDates);

        response.render("show");
    }
}
